import 'package:flutter/material.dart';
import 'package:flutter_example_app/screens/car/car.dart';
import 'package:flutter_example_app/screens/home/home.dart';
import 'package:flutter_example_app/screens/profile/profile.dart';
import 'package:flutter_example_app/screens/shopping/shopping.dart';
import 'package:flutter_snake_navigationbar/flutter_snake_navigationbar.dart';

class Tabbar extends StatefulWidget {
  const Tabbar({super.key});

  @override
  State<Tabbar> createState() => _TabbarState();
}

class _TabbarState extends State<Tabbar> with SingleTickerProviderStateMixin {
  // 当前tabbar索引
  int currentIndex = 0;
  late TabController tabController;

  @override
  void initState() {
    tabController = TabController(length: 4, vsync: this);
    // tabController.addListener(() {
    //   setState(() {
    //     currentIndex = tabController.index;
    //   });
    // });
    super.initState();
  }

  dynamic handleTabChange(int index) {
    setState(() {
      currentIndex = index;
      tabController.animateTo(index); // 同步控制器
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: TabBarView(
        controller: tabController,
        // 页面滚动行为的物理效果
        physics: const NeverScrollableScrollPhysics(),
        children: const <Widget>[Home(), Shopping(), Car(), Profile()],
      ),
      bottomNavigationBar: SnakeNavigationBar.color(
        behaviour: SnakeBarBehaviour.floating,
        snakeShape: SnakeShape.circle,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
        padding: const EdgeInsets.all(12),
        backgroundColor: Colors.blueGrey,
        selectedItemColor: Colors.white,
        unselectedItemColor: Colors.blueGrey.withOpacity(0.5),
        currentIndex: currentIndex,
        onTap: (index) => handleTabChange(index),
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'),
          BottomNavigationBarItem(icon: Icon(Icons.search), label: '搜索'),
          BottomNavigationBarItem(icon: Icon(Icons.favorite), label: '收藏'),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'),
        ],
      ),
    );
  }
}
